// src/services/menuApiService.js
import * as menuApi from '@/api/menu';
import {useDataActions} from "@/services/useDataActions";
import { useFormActions } from '@/services/useFormActions'
import {computed} from "vue";
import { useMenuStore } from '@/stores/menuStore';

// 定义菜单表单字段
const menuFields = [
  'id',
  'name',
  'path',
  'component',
  'icon',
  'order_num',
  'hidden',
  'keep_alive',
  'redirect',
  'parent_id'
]

// 表单操作
export function useMenuFormActions({ onMenuChange = () => {} }) {
  const menuStore = useMenuStore();
  
  // 使用表单控制逻辑
  const { formVisible, currentFormData, openForm} = useFormActions({
    fields: menuFields
  })

  // 直接更新 store 的方法
  const updateStoreData = async (type, data) => {
    switch(type) {
      case 'add':
        menuStore.addMenuItem(data);
        break;
      case 'update':
      case 'updateField':
        // 修改这里：使用 await 等待 fetchMenu 完成
        await menuStore.fetchMenu(true);
        break;
      case 'delete':
        menuStore.deleteMenuItem(data.id);
        break;
    }
    onMenuChange(type, data);
  };

  // 封装表单提交
  const { handleFormSubmit, handleDelete, handleFieldUpdate } = useDataActions({
    api: {
      add: menuApi.createMenu,
      update: menuApi.updateMenu,
      delete: menuApi.deleteMenu
    },
    // 直接更新 store 数据
    onActionSuccess: updateStoreData,
    messages: {
      add: '新增菜单成功',
      update: '编辑菜单成功',
      delete: '删除菜单成功',
      updateField: '字段更新成功'
    }
  });

  return {
    formVisible,
    currentFormData,
    openForm,
    handleFormSubmit,
    handleDelete,
    handleFieldUpdate
  };
}

// 菜单列表数据
export function useMenuListData(menuStore, filter) {
  // 递归过滤菜单树
  function filterMenuTreeRecursively(tree, filterValue) {
    return tree.reduce((acc, node) => {
      if (!node) return acc

      const hasNameMatch = !filterValue.name || node.name?.includes(filterValue.name)
      const hasComponentMatch = !filterValue.component || node.component?.includes(filterValue.component)
      const match = hasNameMatch && hasComponentMatch

      // 递归处理子节点
      const children = node.children ? filterMenuTreeRecursively(node.children, filterValue) : []

      // 如果当前节点匹配或有匹配的子节点，则保留该节点
      if (match || children.length) {
        acc.push({ ...node, children })
      }

      return acc
    }, [])
  }

  const filteredMenuTree = computed(() => {
    const menuTree = menuStore.getMenuTree || []

    if (!filter.value.name && !filter.value.component) {
      return menuTree
    }

    return filterMenuTreeRecursively(menuTree, filter.value)
  })

  return { filteredMenuTree }
}